package com.cloudweb.oa.security;

import cn.js.fan.util.StrUtil;
import cn.js.fan.web.Global;
import cn.ljserver.tool.weboffice.v3.config.WebOfficeProperties;
import com.alibaba.fastjson.JSONObject;
import com.cloudweb.oa.api.ILicense;
import com.cloudweb.oa.api.ILicenseUtil;
import com.cloudweb.oa.config.JwtProperties;
import com.cloudweb.oa.service.LoginService;
import com.cloudweb.oa.utils.*;
import com.cloudwebsoft.framework.util.LogUtil;
import com.redmoon.oa.sms.SMSFactory;
import com.redmoon.oa.ui.PortalDb;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Vector;

/**
 * @author
 * @create 2019/1/13 12:59
 * @desc
 **/
@Component
public class LoginSuccessAuthenticationHandler implements AuthenticationSuccessHandler {

    @Autowired
    LoginService loginService;

    @Autowired
    JwtUtil jwtUtil;

    @Autowired
    JwtProperties jwtProperties;

    @Autowired
    SysUtil sysUtil;

    @Autowired
    SysProperties sysProperties;

    @Autowired
    ILicense license;

    @Autowired
    ILicenseUtil licenseUtil;

    @Autowired
    WebOfficeProperties webOfficeProperties;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String str = null;
        try {
            if (loginService==null) {
                loginService = SpringUtil.getBean(LoginService.class);
            }
            str = loginService.login(request, response, authentication);
        }
        catch (JSONException e) {
            LogUtil.getLog(getClass()).error(e);
        }

        String authToken = jwtUtil.generate(authentication.getName());

        response.setHeader(jwtProperties.getHeader(), authToken);

        JSONObject json = JSONObject.parseObject(str);
        json.put("code", 200);
        json.put(jwtProperties.getHeader(), authToken);

        com.redmoon.oa.Config cfg = com.redmoon.oa.Config.getInstance();
        JSONObject jsonObject = sysUtil.getServerInfo();

        // 用户的首页门户
        PortalDb pd = new PortalDb();
        pd = (PortalDb)pd.getQObjectDb(PortalDb.DESKTOP_DEFAULT_ID);

        String userName;
        // 如果是 WebSecurityConfig中configure的是DaoAuthenticationProvider，则authentication取到的是org.springframework.security.core.userdetails.User
        if (authentication.getPrincipal() instanceof org.springframework.security.core.userdetails.User) {
            userName = ((org.springframework.security.core.userdetails.User) authentication.getPrincipal()).getUsername();
        } else {
            userName = (String) authentication.getPrincipal();
        }

        boolean canSeeHome = pd.canUserSee(userName) && pd.getInt("status") == 1;
        if (canSeeHome) {
            jsonObject.put("portalId", PortalDb.DESKTOP_DEFAULT_ID);
        } else {
            int portalId = PortalDb.DESKTOP_DEFAULT_ID;
            Vector<PortalDb> v = pd.listByKind(PortalDb.KIND_DESKTOP);
            for (PortalDb portalDb : v) {
                if (portalDb.canUserSee(userName)) {
                    portalId = portalDb.getInt("id");
                    break;
                }
            }
            jsonObject.put("portalId", portalId);
        }

        // 菜单项所属的应用
        jsonObject.put("isMenuGroupByApplication", cfg.getBooleanProperty("isMenuGroupByApplication"));
        jsonObject.put("isExportExcelAsync", sysProperties.isExportExcelAsync());        
		jsonObject.put("isObjStoreEnabled", sysProperties.isObjStoreEnabled());
        // 是否启用悬浮进度栏
        jsonObject.put("isUploadPanel", sysProperties.isUploadPanel());
        // 是否启用悬浮按钮，如果为否，则使用顶栏的按钮
        jsonObject.put("isUploadPanelBtnSuspension", sysProperties.isUploadPanelBtnSuspension());

        String version = StrUtil.getNullStr(cfg.get("version"));
        com.redmoon.oa.SpConfig spCfg = new com.redmoon.oa.SpConfig();
        String spVersion = StrUtil.getNullStr(spCfg.get("version"));
        // 系统版本
        jsonObject.put("version", version);
        // 补丁版本
        jsonObject.put("spVersion", spVersion);
        // OA版本：标准版、专业版、企业版等
        jsonObject.put("versionType", license.getVersionType());
        jsonObject.put("isCloud", cfg.getBooleanProperty("isCloud"));
        int refreshOnlineUserNotify = cfg.getInt("refreshOnlineUserNotify"); // 用户每隔多长时间，向服务器通报一次在线（秒）
        jsonObject.put("refreshOnlineUserNotify", refreshOnlineUserNotify);
        String refreshMessage = cfg.get("refresh_message");
        jsonObject.put("refreshMessage", refreshMessage);
        boolean isWatermark = cfg.getBooleanProperty("isWatermark");
        jsonObject.put("isWatermark", isWatermark);
        // 系统是否处于调试状态
        jsonObject.put("isDebug", Global.getInstance().isDebug());
        jsonObject.put("isUseSms", SMSFactory.isUseSMS());

        int formEditorType = cfg.getInt("formEditorType");
        // 如果不允许使用业务表单，则强制为0，即只能使用专业表单
        if (!licenseUtil.isEnabled(LicenseConstUtil.FORM_DESIGNER)) {
            formEditorType = 0;
        }
        jsonObject.put("formEditorType", formEditorType);
        jsonObject.put("isUseClient", cfg.getBoolean("isUseClient"));

        jsonObject.put("webOfficeAppId", webOfficeProperties.getConvert().getAppid());

        jsonObject.put("isUseBreakpointResume", cfg.getBoolean("isUseBreakpointResume"));

        json.put("serverInfo", jsonObject);

        //设置返回请求头
        response.setContentType("application/json;charset=utf-8");
        //写出流
        PrintWriter out = response.getWriter();
        out.write(json.toJSONString());
        out.flush();
        out.close();
    }
}
